package cn.liu.jetpack_demo.api

import android.util.Log
import cn.liu.jetpack_demo.models.ResultModel
import cn.liu.jetpack_demo.models.UserModel
import cn.liu.jetpack_demo.utils.HttpUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.awaitResponse
import retrofit2.http.Body
import retrofit2.http.POST

data class LoginRequest(
    val username: String,
    val password: String
)

interface IPassportApi {
  @POST("passport/login")
  fun login(@Body rquest: LoginRequest): Call<ResultModel<UserModel>>

    companion object {
        // 创建一个Retrofit实例
        fun create(): IPassportApi {
            return HttpUtil.createService(IPassportApi::class.java)
        }
    }
}
object PassportApi {
    /// 同步调用接口
    suspend fun login(username: String, password: String): UserModel? {
//        CoroutineScope(Dispatchers.IO).launch {
            val result: Response<ResultModel<UserModel>> = IPassportApi.create().login(LoginRequest(username, password)).awaitResponse()
            if(result.isSuccessful) {
                val res: ResultModel<UserModel>? = result.body()!!
                Log.d("AppScreen", "onResponse: $res")
                if (res != null) {
                    return res.data
                }
            }
//        }
        return null
    }

    /// 异步调用接口
     suspend fun syncLogin(username: String, password: String, callback: (result: UserModel?) -> Unit) {
        try {
            CoroutineScope(Dispatchers.IO).launch {
                IPassportApi.create().login(LoginRequest(username, password)).enqueue(object : Callback<ResultModel<UserModel>> {
                    override fun onResponse(
                        call: Call<ResultModel<UserModel>>,
                        response: Response<ResultModel<UserModel>>
                    ) {
                        if (response.isSuccessful) {
                            val res: ResultModel<UserModel>? = response.body()!!
                            Log.d("AppScreen", "onResponse: $res")
//                            if (res != null) {
                                callback(res?.data)
//                            }
                        }
                    }

                    override fun onFailure(call: Call<ResultModel<UserModel>>, t: Throwable) {
                        Log.d("login", "error: $t")
                    }

                })
            }
//                Log.d("PassportApi login", "response: $response")
//            if (response.isSuccessful) {
//                val data = response.body()
//                // 处理数据
//            } else {
//                // 处理错误响应
//            }

        } catch (e: Exception) {
            // 处理网络或其他异常
        }
    }
}